package com.info.examples.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class PromoteStrategyFactory implements ApplicationContextAware {

    private Map<PromoteTypeEnum, PromoteSalesService> PROMOTE_MAP = new ConcurrentHashMap<>(1 << 2);

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        // 通过 ApplicationContext 获取到所有 PromoteSalesService 的实例对象
        final Map<String, PromoteSalesService> beans = context.getBeansOfType(PromoteSalesService.class);
        // 把促销类型和具体的实现类形成映射关系存储到map
        beans.values().forEach(bean -> PROMOTE_MAP.put(bean.getType(), bean));
    }

    /**
     * 根据促销类型获取对应的实现
     *
     * @param promoteType
     * @return
     */
    public PromoteSalesService getInstance(PromoteTypeEnum promoteType) {
        return PROMOTE_MAP.get(promoteType);
    }
}
